﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Mapping Application Block
//===============================================================================

using System.Linq;
using System.Configuration;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.ObjectBuilder2;
using EntLibContrib.Mapping.Mappers;
using EntLibContrib.Mapping.Maps;

namespace EntLibContrib.Mapping.Configuration.Unity
{
	/// <summary>
	/// This type supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
	/// Represents the process to create the container policies required to create a <see cref="BasicMapper"/>.
	/// </summary>
	public sealed class BasicMapperPolicyCreator : IContainerPolicyCreator
	{
		#region Public Methods
		/// <summary>
		/// Adds the policies required to create the provider specified by <paramref name="configurationObject"/>
		/// to <paramref name="policyList"/>.
		/// </summary>
		/// <param name="policyList">The <see cref="T:Microsoft.Practices.ObjectBuilder2.IPolicyList"/> to which the policies must be added.</param>
		/// <param name="instanceName">The name to use for the instance's policies.</param>
		/// <param name="configurationObject">The <see cref="T:System.Configuration.ConfigurationElement"/> that describes a provider.</param>
		/// <param name="configurationSource">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource"/> from which additional configuration information
		/// should be retrieved if necessary.</param>
		void IContainerPolicyCreator.CreatePolicies(IPolicyList policyList,
																								string instanceName,
																								ConfigurationElement configurationObject,
																								IConfigurationSource configurationSource)
		{
			BasicMapperData castConfigurationObject = (BasicMapperData)configurationObject;

			// create the maps
			MapDictionary maps = new MapDictionary();
			foreach (MapData map in castConfigurationObject.Maps)
			{
				maps.Add(map.Name, new Map(map.Name, map.ColumnName));
			}

			new PolicyBuilder<BasicMapper, BasicMapperData>(instanceName,
																											castConfigurationObject,
																											c => new BasicMapper(c.Name,
																																					c.TableName,
																																					c.DomainObjectTypeName,
																																					maps,
																																					MappingAssemblerHelper.CreateInstrumentationProvider(c.Name, configurationSource, null))
																											).AddPoliciesToPolicyList(policyList);
		}
		#endregion
	}
}
